package com.fyzk.activity.lottery.recommend_order;

import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.SimpleClickListener;
import com.fyzk.activity.BluePrintDetailsActivity;
import com.fyzk.activity.app.ActivityTaskManager;
import com.fyzk.activity.app.AppToast;
import com.fyzk.activity.popupwindow.FollowDocumentaryPopupWindow;
import com.fyzk.activity.user.LoginActivity;
import com.fyzk.adapter.OtherCenterAdapter;
import com.fyzk.base.BaseActivity;
import com.fyzk.data.AppLotteryInfos;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.net.Commands;
import com.fyzk.utils.AppUtil;
import com.fyzk.utils.CheckClickUtils;
import com.fyzk.utils.DensityUtils;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.utils.SpanUtils;
import com.fyzk.utils.TimeUtil;
import com.fyzk.view.TopTitleView;
import com.fyzk.view.ViewCallBack;
import com.fyzk.view.widget.CustomLoadMoreView;
import com.fyzk.view.widget.DividerItemDecoration;
import com.tyjc.lottery.R;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.List;

import http.Common.CommandUtil;
import http.DataUtil.text.TextUtil;
import http.StringResultBean;

/**
 * 他的中心，新版。
 */
@ContentView(R.layout.activity_other_center)
public class OtherCenterActivity extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener {
    @ViewInject(R.id.ttv_other_center)
    TopTitleView mTtvOtherCenter;
    @ViewInject(R.id.iv_avatar)
    ImageView mIvAvatar;
    @ViewInject(R.id.tv_username)
    TextView mTvUserName;
    @ViewInject(R.id.tv_fans)
    TextView mTvFans;
    @ViewInject(R.id.tv_attention)
    ImageView mIvAttention;
    @ViewInject(R.id.tv_score_a_hit)
    TextView mTvScoreAHit;
    @ViewInject(R.id.tv_hit_profits)
    TextView mTvHitProfits;
    @ViewInject(R.id.tv_award)
    TextView mTvAward;
    @ViewInject(R.id.tv_number)
    TextView mTvNumber;
    @ViewInject(R.id.rv_other_center)
    RecyclerView mRvOtherCenter;
    @ViewInject(R.id.ll_recently_info)
    LinearLayout mLlRecentlyInfo;
    @ViewInject(R.id.tv_recently_hit_profits)
    TextView mTvRecentlyHitProfits;

    private int currentPage = 0;
    private int dataCount = 20;

    private String mUserNo;
    private int mIsExpert;

    //    private MyRecommendOrderBean mInfo;
    private LinearLayoutManager mOtherCenterLayoutManager;
    private OtherCenterAdapter mAdapter;

    private int mCurrentSizeData = 0;

    private int mIsAttention = 2;//是否已关注

    /**
     * 初始化数据
     */
    @Override
    public void initViews() {
        super.initViews();
        mUserNo = getIntent().getStringExtra(IntentParamUtils.USERNO);
        mIsExpert = getIntent().getIntExtra("isExpert", 0);
//        mInfo = (MyRecommendOrderBean) getIntent().getSerializableExtra(IntentParamUtils.RECOMMENDINFOR);
        mTtvOtherCenter.setOnTitleClickListener(this);
        mTtvOtherCenter.getBackView().setImageResource(R.drawable.icon_back_white);
        mIvAttention.setOnClickListener(this);
        mOtherCenterLayoutManager = new LinearLayoutManager(this);
        mRvOtherCenter.setLayoutManager(mOtherCenterLayoutManager);
        mAdapter = new OtherCenterAdapter();
        mRvOtherCenter.setAdapter(mAdapter);
        mAdapter.setOnLoadMoreListener(this, mRvOtherCenter);
        mAdapter.setLoadMoreView(new CustomLoadMoreView());
        mAdapter.setPreLoadNumber(3);
        mAdapter.loadMoreEnd(false);
        mAdapter.setNewData(null);
        mAdapter.setEmptyView(R.layout.layout_empty_plan, mRvOtherCenter);
        mRvOtherCenter.addOnItemTouchListener(new RVItemClickLister());
        DividerItemDecoration decoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        decoration.setDrawable(getDrawable(R.drawable.item_divide_f4f5f6));
        mRvOtherCenter.addItemDecoration(decoration);
        loadHeadData(false);
        loadData(true);
    }

    /**
     * 加载顶部网络数据
     */
    private void loadHeadData(boolean isShowProgress) {
        JSONObject request_json = new JSONObject();
        try {
            request_json.put("userno", mUserNo);
            httpPostJson(CommandUtil.FINDRECOMMENDEDRANKUSERDETAIL, Commands.FINDRECOMMENDEDRANKUSERDETAIL, request_json,
                    isShowProgress);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 加载宣言数据
     *
     * @param isShowProgress 是否显示loading
     */
    private void loadData(boolean isShowProgress) {
        JSONObject request_json = new JSONObject();
        try {
            request_json.put("userno", mUserNo);
            request_json.put("startLine", currentPage);
            request_json.put("maxLine", dataCount);
            httpPostJson(CommandUtil.FINDRECOMMENDEDRANKUSERORDERS, Commands.FINDRECOMMENDEDRANKUSERORDERS, request_json,
                    isShowProgress);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void initData(MyRecommendBean mUserInfo) {
        mUserInfo.setIsexpert(mIsExpert);
//        String recentStatus = "近期状态：" + mUserInfo.getTotalCount() + "中" + mUserInfo.getWinCount();
//        Spannable spannable = new SpannableString(recentStatus);
//        spannable.setSpan(new AbsoluteSizeSpan((int) DensityUtils.sp2px(getResources(), 15)), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//        spannable.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.color_111111)), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//        spannable.setSpan(new ForegroundColorSpan(Color.parseColor("#fffd4a4a")), 5, recentStatus.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        mTvUserName.setText(mUserInfo.getUserName());

        setRecentlyInfoText(mTvAward, "中奖彩金", AppUtil.formatToYuanLXS(mUserInfo.getTotalWinAmount() / 100) + "米");
        setRecentlyInfoText(mTvScoreAHit, "命中率", AppUtil.formatToYuanLXS(mUserInfo.getHitRatio() * 100) + "%");
        setRecentlyInfoText(mTvHitProfits, "盈利率", AppUtil.formatToYuanLXS(mUserInfo.getProfitRatio() * 100) + "%");
        setRecentlyInfoText(mTvNumber, "带红人数", TextUtils.isEmpty(mUserInfo.getBeltRedCount()) ? "0" : mUserInfo.getBeltRedCount());
//        mTvScoreAHit.setText(AppUtil.formatToYuanLXS(mUserInfo.getHitRatio() * 100) + "%");
//        mTvHitProfits.setText(AppUtil.formatToYuanLXS(mUserInfo.getProfitRatio() * 100) + "%");
//        mTvAward.setText(AppUtil.formatToYuanLXS(mUserInfo.getTotalWinAmount() / 100) + "米");
//        mTvNumber.setText(mUserInfo.getBeltRedCount() + "人");

        mLlRecentlyInfo.setVisibility(View.VISIBLE);
        mTvRecentlyHitProfits.setVisibility(View.GONE);
        SpanUtils.with(mTvRecentlyHitProfits)
                .appendLine(AppUtil.formatToYuanLXS(mUserInfo.getProfitRatio() * 100) + "%")
                .setForegroundColor(getResources().getColor(R.color.color_fe4a4b))
                .setFontSize(30, true)
                .append("近15天盈利")
                .setForegroundColor(getResources().getColor(R.color.color_999999))
                .setFontSize(13, true)
                .create();

        String mFansStr = "粉丝：" + (TextUtils.isEmpty(mUserInfo.getFollowCount()) ? "0" : mUserInfo.getFollowCount());
        mTvFans.setText(mFansStr);
        mIsAttention = mUserInfo.getStatus();
        if (1 == mIsAttention) {
            mIvAttention.setImageResource(R.drawable.icon_yet_attention_god);
        } else {
            mIvAttention.setImageResource(R.drawable.icon_attention_god);
        }
        Glide.with(this)
                .load(mUserInfo.getUserPhotoUrl())
                .circleCrop()
                .error(R.drawable.rr_header_icon)
                .placeholder(R.drawable.rr_header_icon)
                .into(mIvAvatar);
        mTtvOtherCenter.setCenterText(isSelf() ? R.string.my_center : R.string.his_center);
        if (!TextUtil.isEmpty(mUserNo) && null != mIvAttention && isSelf()) {
            mIvAttention.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 是否是自己
     *
     * @return
     */
    private boolean isSelf() {
        return TextUtils.equals(mUserNo, MySharedPreferences.getInstance().getUserNo());
    }

    private void setRecentlyInfoText(TextView textView, String title, String content) {
        SpanUtils.with(textView)
                .appendLine(content)
                .setForegroundColor(getResources().getColor(R.color.color_fe4a4b))
                .setFontSize(16, true)
                .append(title)
                .setForegroundColor(getResources().getColor(R.color.color_999999))
                .setFontSize(12, true)
                .create();
    }

    /**
     * 网络加载成功
     *
     * @param requestCode
     * @param resultBean
     * @param result
     */
    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        switch (requestCode) {
            case CommandUtil.FINDRECOMMENDEDRANKUSERDETAIL:
                MyRecommendBean mUserInfo = JSON.parseObject(resultBean.getData(), MyRecommendBean.class);
                initData(mUserInfo);
                break;
            case CommandUtil.FINDRECOMMENDEDRANKUSERORDERS:
                List<MyRecommendOrderBean> mData = JSON.parseArray(resultBean.getData(), MyRecommendOrderBean.class);
                if (mData == null || mData.size() == 0) {
                    mAdapter.loadMoreEnd();
                    mCurrentSizeData = 0;
                } else {
                    mCurrentSizeData = mData.size();
                    for (MyRecommendOrderBean mDatum : mData) {
                        mDatum.setFollowCount(mDatum.getFollowTotalNumber());
                    }
                    if (currentPage == 0) {
                        mAdapter.setNewData(mData);
                        mAdapter.disableLoadMoreIfNotFullPage();
                    } else {
                        mAdapter.addData(mData);
                        mAdapter.loadMoreComplete();
                    }
                }
                break;
            case CommandUtil.USERFOLLOWER:
                if (1 == mIsAttention) {
                    AppToast.getToast().show("取消成功");
                    mIvAttention.setImageResource(R.drawable.icon_attention_god);
                    mIsAttention = 2;
                    notifyAttentionNum(false);
                } else {
                    AppToast.getToast().show("关注成功");
                    mIvAttention.setImageResource(R.drawable.icon_yet_attention_god);
                    mIsAttention = 1;
                    notifyAttentionNum(true);
                }
                break;
        }
    }


    /**
     * 网络加载失败
     *
     * @param requestCode
     * @param errorCode
     * @param message
     */
    @Override
    protected void onFailure(int requestCode, String errorCode, String message) {
        super.onFailure(requestCode, errorCode, message);
        switch (requestCode) {
            case CommandUtil.FINDRECOMMENDEDRANKUSERORDERS:
                mCurrentSizeData = 0;
                if (0 == currentPage) {
                    mAdapter.setNewData(null);
                    mAdapter.setEmptyView(R.layout.layout_end_of_video_rv, mRvOtherCenter);
                } else {
                    mAdapter.loadMoreFail();
                }
                break;
            case CommandUtil.USERFOLLOWER:
                if (1 == mIsAttention) {
                    AppToast.getToast().show("取消失败");
                } else {
                    AppToast.getToast().show("关注失败");
                }
                break;
            default:
                break;
        }

    }

    @Override
    protected void onFailure(int requestCode, String message) {
        super.onFailure(requestCode, message);
        switch (requestCode) {
            case CommandUtil.FINDRECOMMENDEDRANKUSERORDERS:
                mCurrentSizeData = 0;
                if (0 == currentPage) {
                    mAdapter.setNewData(null);
                    mAdapter.setEmptyView(R.layout.layout_end_of_video_rv, mRvOtherCenter);
                } else {
                    mAdapter.loadMoreFail();
                }
                break;
            case CommandUtil.USERFOLLOWER:
                if (1 == mIsAttention) {
                    AppToast.getToast().show("取消失败");
                } else {
                    AppToast.getToast().show("关注失败");
                }
                break;
        }
    }


    /**
     * 加载下一页
     */
    @Override
    public void onLoadMoreRequested() {
        currentPage += mCurrentSizeData;
        loadData(false);
    }

    @Override
    public void onClick(View arg0) {
        super.onClick(arg0);
        switch (arg0.getId()) {
            case R.id.tv_attention:
                if (!CheckClickUtils.isFastClick()) {
                    if (MySharedPreferences.getInstance().getLoginStatus()) {
                        if (mIsAttention == 1) {
                            sendAttentionOrCancelAttentionGod(2);
                        } else {
                            sendAttentionOrCancelAttentionGod(1);
                        }
                    } else {
                        AppLotteryInfos.clear();
                        ViewCallBack.getInstance().countDownObjs.clear();
                        ActivityTaskManager.getInstance().closeAllActivity();
                        Intent intent = new Intent(getContext(), LoginActivity.class);
                        startActivity(intent);
                    }
                }
                break;
        }
    }

    private class RVItemClickLister extends SimpleClickListener {

        @Override
        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
            MyRecommendOrderBean item = mAdapter.getItem(position);
            if (null == item)
                return;
//            if (!isSelf() && !(item.getWay() == 2 && item.getOrderResultStatus() == 5)) {
//                showToast("已经截止");
//                return;
//            }
            Intent intent = new Intent(getContext(), BluePrintDetailsActivity.class);
            intent.putExtra(IntentParamUtils.USERNO, mUserNo);
            intent.putExtra(IntentParamUtils.RECOMMENDINFOR, item);
            startActivity(intent);
        }

        @Override
        public void onItemLongClick(BaseQuickAdapter adapter, View view, int position) {

        }

        @Override
        public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
            MyRecommendOrderBean item = mAdapter.getItem(position);
            switch (view.getId()) {
                case R.id.tv_follow://跟单
                    showFollowDocumentaryPopup(item);
                    break;
            }
        }

        @Override
        public void onItemChildLongClick(BaseQuickAdapter adapter, View view, int position) {

        }
    }

    FollowDocumentaryPopupWindow followDocumentaryPopupWindow;

    /**
     * 展示跟单的弹窗
     *
     * @param item 跟单内容
     */
    private void showFollowDocumentaryPopup(MyRecommendOrderBean item) {
        if (null == item || !(item.getOrderResultStatus() == 5
                && System.currentTimeMillis() < TimeUtil.stringToLong(item.getEndTime()))) {
            showToast("已经截止");
            return;
        }
        followDocumentaryPopupWindow = new FollowDocumentaryPopupWindow(getContext(), item);
        followDocumentaryPopupWindow.showPopupWindow();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (1000 == requestCode) {
            loadHeadData(false);
            loadData(false);
        }
    }

    /**
     * 关注或者取消关注大神
     *
     * @param isAttention 1关注  2取关
     */
    private void sendAttentionOrCancelAttentionGod(int isAttention) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("userno", MySharedPreferences.getInstance().getUserNo());
            jsonObject.put("followerUserno", mUserNo);
            jsonObject.put("status", isAttention);
            httpPostJson(CommandUtil.USERFOLLOWER, Commands.USERFOLLOWER, jsonObject, true);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 刷新关注数
     *
     * @param isPlus 是加1还是减1
     */
    private void notifyAttentionNum(boolean isPlus) {
        if (null == mTvFans) {
            return;
        }
        String mFans = mTvFans.getText().toString();
        if (mFans.length() > 3) {
            String mFansNum = mFans.substring(3);
            if (mFansNum.length() < 1) {
                return;
            }
            int mIntFansNum = Integer.valueOf(mFansNum);
            if (isPlus) {
                mIntFansNum++;
            } else {
                if (mIntFansNum > 0) {
                    mIntFansNum--;
                }
            }
            String mFansStr = "粉丝：" + mIntFansNum;
            mTvFans.setText(mFansStr);
        }
    }

    @Override
    protected int getStatusBarColor() {
        return R.color.color_fe4a4b;
    }
}
